package trace_log

//通用日志
import (
	"fmt"
	"os"
	"path/filepath"
	"sync"
	"time"
)

var (
	CommonLogger *TLog
	ErrorLogger  *TLog
	logMap       sync.Map
)

// GetAppAbsPath 获取app进程运行的绝对路径
func GetAppAbsPath() (path string, err error) {
	/*	path, err = filepath.Abs(filepath.Dir(os.Args[0]))
		if err != nil {
			fmt.Println("failed get app abs path,err:", err)
			return
		}*/
	return ".", nil
}

func init() {
	appPath, err := GetAppAbsPath()
	if err != nil {
		fmt.Println("[ERROR] failed to get app abs path,err:", err)
		os.Exit(1)
	}
	logPath := filepath.Join(appPath, "log")

	logMap = sync.Map{}

	// 通用日志
	commonLogger, err := NewFileLog(logPath, "common.log", 1)
	if err != nil {
		fmt.Println("[ERROR] failed to new common log,err:", err)
		os.Exit(1)
	}

	CommonLogger = NewLog(commonLogger, 1)

	// error log
	errorLogger, err := NewFileLog(logPath, "error.log", 1)
	if err != nil {
		fmt.Println("[ERROR] failed to new error log,err:", err)
		os.Exit(1)
	}
	ErrorLogger = NewLog(errorLogger, 1)

	// 定时检查
	go polling()
	return
}

// DebugLogger 通用日志
func DebugLogger(sn string, args ...interface{}) {
	defer ExceptionCatch()

	if v, ok := logMap.Load(sn); ok {
		v.(*TLog).Info(args...)
		return
	}

	logPath := filepath.Join(".", "file_log")
	logger, err := NewFileLog(logPath, fmt.Sprintf("%v.log", sn), 1)
	if err != nil {
		return
	}

	_logger := NewLog(logger, 1)
	logMap.Store(sn, _logger)

	args = append(args, sn)
	_logger.Info(args...)
}

// CommandLogger 通用日志
func CommandLogger(sn string, args ...interface{}) {
	defer ExceptionCatch()

	key := fmt.Sprintf("%s_cmd", sn)
	if v, ok := logMap.Load(key); ok {
		v.(*TLog).Info(args...)
		return
	}

	logPath := filepath.Join(".", "file_log")

	logger, err := NewFileLog(logPath, fmt.Sprintf("%s_cmd.log", sn), 1)
	if err != nil {
		return
	}

	_logger := NewLog(logger, 1)
	logMap.Store(key, _logger)

	_logger.Info(args...)
}

func polling() {
	defer ExceptionCatch()
	ticker := time.NewTicker(time.Second * 60)
	for {
		select {
		case <-ticker.C:
			logMap.Range(func(key, value interface{}) bool {
				defer ExceptionCatch()
				log := value.(*TLog)
				if log == nil {
					logMap.Delete(key)
					return true
				}

				// 超过十分钟清理一次
				if time.Now().Unix()-log.TimeUnix > 600 {
					logMap.Delete(key)
				}

				return true
			})
		}
	}
}
